# -*- coding: utf-8 -*- 
import cherrypy as _cp
from Cheetah.Template import Template 
import pymongo
from pymongo import Connection   
from pymongo.objectid import ObjectId as _id
import pymongo.json_util
import json  
import time
import os.path 
import Image

from skeleton import SkeletonView
class UserView(SkeletonView): 
    
    def avatar_base(self):
        return _cp.config.get('avatar.path') 
    @_cp.expose
    def index(self):
        return self.avatar()
    
    @_cp.expose
    def img(self,uid=None,size=50):
        if not uid: uid = _cp.session['uid']
        avatar_path = os.path.join(self.avatar_base(),'%s_%s.jpg'%(uid,size))
        if not os.path.exists(avatar_path):
            return '/static/avatar/default.jpg'
        else: return '/static/avatar/%s_%s.jpg'%(uid,size)
        
    @_cp.expose
    def avatar(self): 
        uid =  _cp.session['uid'] 
        avatar = os.path.join(self.avatar_base(),'upload','%s.jpg'%uid)
        avatar_url = '/static/avatar/upload/%s.jpg'%uid
        if not os.path.exists(avatar):
             avatar_url = '/static/avatar/upload/default.jpg'
        body = str(Template(file='www/settings.html',searchList=[{                                              
            'uid': uid,
            'avatar_url': avatar_url,
        }])) 
        return self.skeleton(body)
    
    @_cp.expose
    def upload(self,myFile): 
        uid = _cp.session['uid'] 
        try:
            avatar_path = os.path.join(self.avatar_base(),'upload','%s.jpg'%uid) 
            avatar = open(avatar_path,'wb') 
            while True:
                data = myFile.file.read(1024)
                if not data: break 
                else: avatar.write(data) 
            avatar.close() 
            img = Image.open(avatar_path)
            resized = img.resize((300,300),Image.ANTIALIAS)
            resized.save(avatar_path)
            
        except Exception,e: 
            print e
        raise _cp.HTTPRedirect('/u/avatar/')
    @_cp.expose
    def avatar_crop(self,x1,y1,x2,y2): 
        box = (int(x1),int(y1),int(x2),int(y2))
        uid = _cp.session['uid']  
        avatar_path = os.path.join(self.avatar_base(),'upload','%s.jpg'%uid)
        if not os.path.exists(avatar_path):
            avatar_path = os.path.join(self.avatar_base(),'upload','default.jpg')
        img = Image.open(avatar_path)
        region = img.crop(box)
        img = region.resize((128,128))
        img.save(os.path.join(self.avatar_base(),'%s_128.jpg'%uid))
        img = region.resize((50,50))
        img.save(os.path.join(self.avatar_base(),'%s_50.jpg'%uid))
        img = region.resize((30,30))
        img.save(os.path.join(self.avatar_base(),'%s_30.jpg'%uid))
        
        raise _cp.HTTPRedirect('/u/avatar/')